import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 处理业务的任务
 */
public class BuTask implements Runnable {
    // 要处理的数据
    private ByteBuffer buffer;

    private final SocketChannel socketChannel;


    public BuTask(SocketChannel socketChannel, ByteBuffer buffer) {
        this.socketChannel = socketChannel;
        this.buffer = buffer;
    }

    //处理数据做业务
    @Override
    public void run() {
        //读写转换
        buffer.flip();
        //创建一个字节数组，长度为缓冲区剩余的字节数flowchart TD
        byte[] bytes = new byte[buffer.remaining()];
        //将缓冲区中的数据读取到字节数组中
        buffer.get(bytes);
        //将buffer置为null，释放引用以便垃圾回收。
        buffer = null;
        //数据解码
        String message = new String(bytes, Charset.defaultCharset());
        System.out.println("服务端收到客户端消息："+message);
        //todo 处理业务

        //向客户端返回数据，方便客户端测试
        byte[] bytes1 = "hello,reactor client, i am  reactor server \n".getBytes(StandardCharsets.UTF_8);
        ByteBuffer writeBuffer=ByteBuffer.allocate(bytes1.length);
        writeBuffer.put(bytes1);
        writeBuffer.flip();
        try {
            socketChannel.write(writeBuffer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
